package com.jzlin.alltools.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.Locale;

/**
 * 国际化工具.
 *
 * @author linjz
 * @date 2024/9/14
 */
public class LocaleUtils {
    private static final Logger log = LoggerFactory.getLogger(LocaleUtils.class);
    private static final MessageSource MS = SpringContextUtils.getBean(MessageSource.class);

    public LocaleUtils() {
    }

    public static String getMessage(String code) {
        Locale locale = LocaleContextHolder.getLocale();
        if (MS == null) {
            throw new RuntimeException("locale messsage source can not be null!");
        } else {
            try {
                return MS.getMessage(code, (Object[])null, locale);
            } catch (Exception var3) {
                log.error("code: {} 未定义i18n资源", code);
                return code;
            }
        }
    }

    public static String getMessage(String code, Object... args) {
        Locale locale = LocaleContextHolder.getLocale();
        if (MS == null) {
            throw new RuntimeException("locale messsage source can not be null!");
        } else {
            try {
                return MS.getMessage(code, args, locale);
            } catch (Exception var4) {
                log.error("code: {} 未定义i18n资源", code);
                return code;
            }
        }
    }

    public static String getMessage(String code, Locale locale) {
        if (MS == null) {
            throw new RuntimeException("locale messsage source can not be null!");
        } else {
            try {
                return MS.getMessage(code, (Object[])null, locale);
            } catch (Exception var3) {
                log.error("code: {} 未定义i18n资源", code);
                return code;
            }
        }
    }

    public static String getMessage(String code, Locale locale, Object... args) {
        if (MS == null) {
            throw new RuntimeException("locale messsage source can not be null!");
        } else {
            try {
                return MS.getMessage(code, args, locale);
            } catch (Exception var4) {
                log.error("code: {} 未定义i18n资源", code);
                return code;
            }
        }
    }
}
